package com.feihong.yw189.bluetooth.contral;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.telecom.Call;
import android.util.Log;
import android.view.KeyEvent;

import com.feihong.yw189.R;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.dialog.YqDialog;
import com.feihong.yw189.bluetooth.listener.ReadIccidListener;
import com.feihong.yw189.bluetooth.listener.ResultListener;
import com.feihong.yw189.bluetooth.listener.WriteCardListener;
import com.feihong.yw189.bluetooth.startwritecard.DjlmWrite;
import com.feihong.yw189.bluetooth.startwritecard.HHDWrite;
import com.feihong.yw189.bluetooth.startwritecard.Kt8000Write;
import com.feihong.yw189.bluetooth.startwritecard.Kt8003Write;
import com.feihong.yw189.bluetooth.startwritecard.SenRuiWrite;
import com.feihong.yw189.bluetooth.utils.util.Busi_Idcard_device;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.http.HttpTools;
import com.sunnada.bluetooth.SYDBlueReaderHelper;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import sunrise.bluetooth.SRBluetoothCardReader;

/**
 * Created by yucheng on 2017/11/21.
 */

public class WriteContralCenter {
    private Context mContext;
    private Activity activity;
    private BluetoothAdapter ba;
    private int index;
    private int mType; // 0废卡重置 1写卡 2补卡
    private String orderSn = "";
    private String bleAddress = "";
//    private RefreshWebListener mRefreshWebListener;


    byte[] szImsi = null;

    // 写卡所需
    private Handler senHandler;
    private SRBluetoothCardReader senmBlueReaderHelper;
    public SYDBlueReaderHelper mIdUtil = null;
    public Busi_Idcard_device midHandler = null;
    private Kt8000Write kt8000Write;
    private Kt8003Write kt8003Write;
    private SenRuiWrite senRuiWrite;
    private HHDWrite mHHDWrite;
    private DjlmWrite mDjlmWrite;
    private YqDialog yqDialog;


    private MyUsualyDialog dialog;// 进度条

    private class MyHandler extends Handler {
        private Context mContext;
        private Activity mActivity;

        @SuppressLint("HandlerLeak")
        MyHandler(Context context) {
            this.mContext = context;
            this.mActivity = (Activity) context;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1470:
                    String msgResult = (String) msg.obj;
                    yqDialog.setStr(msgResult);
                    yqDialog.show();
                    senHandler.sendEmptyMessageDelayed(1473, 3000);
                    break;
                case 1471:
                    final String msgResult1 = (String) msg.obj;
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showShortToast(mContext, msgResult1);
                            mResultListener.result(1);
                        }
                    });
                    break;
                case 1472:
                    String sucResult = (String) msg.obj;
                    yqDialog.setStr(sucResult);
                    yqDialog.show();
                    senHandler.sendEmptyMessageDelayed(1474, 3000);
                    break;
                case 1473: // 异常
                    yqDialog.cancel();
                    mResultListener.result(1);
                    break;
                case 1474: // 成功
                    yqDialog.cancel();
                    mResultListener.result(0);
                    break;
            }
        }
    }

    private ResultListener mResultListener;

    /**
     * @param context
     * @param ba
     * @param mType   // 0废卡重置 1写卡 2补卡
     * @param index   //
     * @param orderSn
     */
    public WriteContralCenter(Context context, BluetoothAdapter ba, int mType,
                              int index, String orderSn, ResultListener mResultListener) {
        this.mContext = context;
        this.activity = (Activity) context;
        this.ba = ba;
        this.index = index;
        this.mType = mType;
        this.orderSn = orderSn;
        this.mResultListener = mResultListener;

        initData();
    }


//    /**
//     * @param context
//     * @param ba
//     * @param mType
//     * @param index
//     * @param orderSn
//     * @param mRefreshWebListener // 需要web端刷新的重构
//     */
//    public WriteContralCenter(Context context, BluetoothAdapter ba, int mType, int index, String orderSn,
//                              RefreshWebListener mRefreshWebListener) {
//        this.mContext = context;
//        this.activity = (Activity) context;
//        this.ba = ba;
//        this.index = index;
//        this.mType = mType;
//        this.orderSn = orderSn;
//        this.mRefreshWebListener = mRefreshWebListener;
//        initData();
//    }

    private void initData() {
        dialog = new MyUsualyDialog(mContext, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(true);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                closeConnect();  // 返回键处理
                activity.finish();
                return true;
            }
        });
        yqDialog = new YqDialog(activity);
        yqDialog.setCancelable(true);
        senHandler = new MyHandler(mContext);
    }

    private String mUrl = "";

    public void closeConnect() {
        switch (index) {
            case 0:
                if (kt8000Write != null) {

                    kt8000Write.closeClient();
                }
                break;
            case 1:
                if (kt8003Write != null) {

                    kt8003Write.stopConnect();
                }
                break;
            case 4:
                if (mDjlmWrite != null) {

                    mDjlmWrite.disConnect();
                }
                break;

        }
    }

    public void writeCardStart(String address) {
        this.bleAddress = address;
        dialog.show();// 显示进度条
        switch (index) {
            case 0: // KT8000
                kt8000Write = new Kt8000Write(activity, address, mType,
                        new ReadIccidListener() {
                            @Override
                            public void readIccidSuc(int count, String iccid, String imsi) {
                                if (mType == 0) {
                                    kt8000Write.closeClient();
                                }
                                DJLM_ICCIC_SUCCESS(count, iccid, imsi);
                            }

                            @Override
                            public void readIccidErr(String err) {
                                kt8000Write.closeClient();
                                dismissDialog();
                                showMsg(111, err);
                            }

                            @Override
                            public void readIccidIsChengKa(int index, String iccid, String err) {
                                if (mType == 0) {
                                    kt8000Write.closeClient();
                                }
                                DJLM_ICCIC_SUCCESS(index, iccid, "");
                                showMsg(111, err);
                            }
                        },
                        new WriteCardListener() {
                            @Override
                            public void writeSuc() {
                                kt8000Write.closeClient();

                                DJLMxieruChengGong();
                            }

                            @Override
                            public void writeErr() {

                                kt8000Write.closeClient();

                                DJLMXieRuShiBai();
                            }
                        });
                kt8000Write.connect();
                break;
            case 1: // KT8003

                kt8003Write = new Kt8003Write(activity, address, mType,
                        new ReadIccidListener() {
                            @Override
                            public void readIccidSuc(int count, String iccid, String imsi) {
                                if (mType == 0) {
                                    kt8003Write.stopConnect();
                                }
                                DJLM_ICCIC_SUCCESS(count, iccid, imsi);
                            }

                            @Override
                            public void readIccidErr(String err) {
                                kt8003Write.stopConnect();
                                dismissDialog();
                                showMsg(111, err);
                            }

                            @Override
                            public void readIccidIsChengKa(int index, String iccid, String err) {
                                if (mType == 0) {
                                    kt8003Write.stopConnect();
                                }
                                DJLM_ICCIC_SUCCESS(index, iccid, "");
                                showMsg(111, err);
                            }
                        },
                        new WriteCardListener() {
                            @Override
                            public void writeSuc() {
                                DJLMxieruChengGong();
                            }

                            @Override
                            public void writeErr() {

                                DJLMXieRuShiBai();
                            }
                        });
                kt8003Write.connect();
                break;
            case 2: // 森瑞
                String srSeverIp = PrefUtils.getString(activity, ConstantsValue.SRserverIp, "id.esaleb.com");
                String srAccount = PrefUtils.getString(activity, ConstantsValue.SRaccount, "test01");
                String srPwd = PrefUtils.getString(activity, ConstantsValue.SRpassword, "12315aA..1");
                String srPort = PrefUtils.getString(activity, ConstantsValue.SRport, "6100");
                String srKey = PrefUtils.getString(activity, ConstantsValue.SRkey, "FE870B0163113409C134283661490AEF");
                int srPor = Integer.parseInt(srPort);
                senmBlueReaderHelper = new SRBluetoothCardReader(senHandler, mContext, srSeverIp, srPor,
                        srAccount, srPwd, srKey);
                senRuiWrite = new SenRuiWrite(activity, senmBlueReaderHelper, mType, address,
                        new ReadIccidListener() {
                            @Override
                            public void readIccidSuc(int count, String iccid, String imsi) {

                                DJLM_ICCIC_SUCCESS(count, iccid, imsi);
                            }

                            @Override
                            public void readIccidErr(String err) {
                                dismissDialog();
                                showMsg(111, err);
                            }

                            @Override
                            public void readIccidIsChengKa(int index, String iccid, String err) {
                                DJLM_ICCIC_SUCCESS(index, iccid, "");
                                showMsg(111, err);
                            }
                        },
                        new WriteCardListener() {
                            @Override
                            public void writeSuc() {
                                DJLMxieruChengGong();
                            }

                            @Override
                            public void writeErr() {
                                DJLMXieRuShiBai();
                            }
                        });
                senRuiWrite.connect();
                break;
            case 3: // 恒鸿达
                midHandler = new Busi_Idcard_device(activity);
                mIdUtil = new SYDBlueReaderHelper(midHandler.BmHanddler, activity);
                mHHDWrite = new HHDWrite(activity, mType, midHandler, mIdUtil, address,
                        new ReadIccidListener() {
                            @Override
                            public void readIccidSuc(int count, String iccid, String imsi) {
                                DJLM_ICCIC_SUCCESS(count, iccid, imsi);
                            }

                            @Override
                            public void readIccidErr(String err) {
                                dismissDialog();
                                showMsg(111, err);
                            }

                            @Override
                            public void readIccidIsChengKa(int index, String iccid, String err) {
                                DJLM_ICCIC_SUCCESS(index, iccid, "");
                                showMsg(111, err);
                            }
                        },
                        new WriteCardListener() {
                            @Override
                            public void writeSuc() {
                                DJLMxieruChengGong();
                            }

                            @Override
                            public void writeErr() {
                                DJLMXieRuShiBai();
                            }
                        });
                mHHDWrite.connect();
                break;
            case 4: // 店家联盟
                mDjlmWrite = new DjlmWrite(activity, address, mType,
                        new ReadIccidListener() {
                            @Override
                            public void readIccidSuc(int count, String iccid, String imsi) {

                                DJLM_ICCIC_SUCCESS(count, iccid, imsi);
                            }

                            @Override
                            public void readIccidErr(String err) {
                                dismissDialog();
                                showMsg(111, err);
                            }

                            @Override
                            public void readIccidIsChengKa(int index, String iccid, String err) {
                                DJLM_ICCIC_SUCCESS(index, iccid, "");
                                showMsg(111, err);
                            }
                        },
                        new WriteCardListener() {
                            @Override
                            public void writeSuc() {
                                mDjlmWrite.disConnect();
                                DJLMxieruChengGong();
                            }

                            @Override
                            public void writeErr() {
                                DJLMXieRuShiBai();
                            }
                        });
                mDjlmWrite.connect();
                break;
        }
    }

    private String token = "";
    private String ICCID = "";

    private String oneValue = "";
    private String twoValue = "";
    private String sucUrl = "";
    private String xieOrBu = "";
    private String oneKey = "id";
    private String twoKey = "sn";

    //**********************************读卡成功**************************************
    private void DJLM_ICCIC_SUCCESS(final int count, final String iccid, String imsi) {
        switch (mType) {
            case 0: // 废卡重置
                mUrl = HttpTools.CLEAR_CARD;
                oneKey = "iccid";
                twoKey = "imsi";
                oneValue = iccid;
                twoValue = imsi;
                yqDialog.setTitle("废卡重置结果");
                break;
            case 1: // 写卡
                mUrl = HttpTools.BAI_KA;
                sucUrl = HttpTools.BAI_KA_OK;
                oneValue = iccid;
                twoValue = orderSn;
                xieOrBu = "写卡";
                yqDialog.setTitle("写卡结果");
                break;
            case 2: // 补卡
                mUrl = HttpTools.BU_KA;
                sucUrl = HttpTools.BU_KA_OK;
                oneValue = iccid;
                twoValue = orderSn;
                xieOrBu = "补卡";
                yqDialog.setTitle("补卡结果");
                break;
        }
        Log.e("项目异常", "类型 : " + mType + "---iccid=" + iccid + "---imsi=" + imsi);
        ICCID = iccid;
        RequestParams requestParams = new RequestParams(mUrl);
        requestParams.addBodyParameter(oneKey,oneValue);
        requestParams.addBodyParameter(twoKey,twoValue);
        requestParams.addBodyParameter("token",token);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("写卡", "类型 : " + mType + "----结果---" + result);
                if (count == 1617) {
                    dismissDialog();
                } else {
                    if (mType == 0) {
                        // 废卡重置
                        Log.e("项目异常", "------结果是废卡重置---i---" + mUrl);
                        dismissDialog();
                        clearCard(result);
                    } else {
                        showMsg(111, "读取iccid成功,开始" + xieOrBu);
                        Log.e("项目异常", "------结果是补/写卡------" + mUrl);
                        // 补卡,写卡
                        WriteCardResult(result, count);   // 暂时注释掉
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                dismissDialog();
                if (count == 4) {
                    mDjlmWrite.disConnect();
                } else if (count == 0) {
                    kt8000Write.closeClient();
                } else if (count == 1) {
                    kt8003Write.stopConnect();
                }
                showMsg(111, "网络或服务器错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void clearCard(String s) {
        try {
            JSONObject json = new JSONObject(s);
            int code = json.getInt("code");
            String result = "";
            switch (code) {
                case 3101: // 返回读取失败
                    result = "重置失败:" + json.getString("msg");
                    break;
                case 3102: // 返回false
                    result = "重置失败:" + json.get("msg");
                    if (result.contains("卡片已置为可用状态")) {
                        result = "重置成功";
                    }
                    break;
                case 200: // 重置成功
                    result = json.getString("msg");
                    // 成功的返回码是啥
                    break;
            }
            Log.e("项目异常", "------result------" + result);
            showMsg(112, result);
        } catch (JSONException e) {
            e.printStackTrace();
            showMsg(111, "数据解析异常");
        }
    }

    private void WriteCardResult(String s, int count) {
        try {
            JSONObject json = new JSONObject(s);
            int status = json.getInt("status");
            Log.e("项目异常", "--count=" + count + "--status=" + status);
            if (status == 1) {
                // 成功
                JSONObject msg = json.getJSONObject("msg");
                String IMSI = msg.getString("imsi");
                String Send_number = msg.getString("send_number");

                if (count == 0) {
                    // kt8000写卡方式
                    szImsi = IMSI.getBytes();
                    kt8000Write.writeKEardTask(szImsi, Send_number);
                } else if (count == 1) {
                    // KT8003写卡方式
                    szImsi = IMSI.getBytes();
                    kt8003Write.writeIMSICardTask(szImsi, Send_number);

                } else if (count == 2) {
                    // 森锐写卡方式
                    if (senmBlueReaderHelper.registerBlueCard(bleAddress)) {
                        senRuiWrite.writeICCIDTask(IMSI, Send_number);
                    }
                } else if (count == 3) {
                    // 恒鸿达写卡方式
                    mHHDWrite.writeIccidData(IMSI, "+86" + Send_number);
                } else if (count == 4) {
                    // 店家联盟写卡方式
                    mDjlmWrite.writeCard(IMSI, Send_number);
                }
            } else {
                // 失败
                String msg = json.getString("msg");
                showMsg(112, msg);
                dismissDialog();
                if (count == 4) {
                    mDjlmWrite.disConnect();
                } else if (count == 0) {
                    kt8000Write.closeClient();
                } else if (count == 1) {
                    kt8003Write.stopConnect();
                }
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
            dismissDialog();
            if (count == 4) {
                mDjlmWrite.disConnect();
            } else if (count == 0) {
                kt8000Write.closeClient();
            } else if (count == 1) {
                kt8003Write.stopConnect();
            }
            DJLMXieRuShiBai();
        }
    }
    //************************************* 写卡成功*****************************************

    private void DJLMxieruChengGong() {
        Log.e("项目异常", "------sucUrl------" + sucUrl);
        RequestParams requestParams = new RequestParams(sucUrl);
        requestParams.addBodyParameter("sn",orderSn);
        requestParams.addBodyParameter("sim",ICCID);
        requestParams.addBodyParameter("token",token);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("写卡", "------写卡------" + result);
                dismissDialog();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String status = jsonObject.getString("status");
                    if ("1".equals(status)) {
                        showMsg(113, xieOrBu + "成功");
                    } else {
                        String msg = jsonObject.getString("msg");
                        showMsg(112, msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showMsg(112, "写卡失败,数据解析异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                dismissDialog();
                showMsg(111, "网络或服务器错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 写卡失败
     */
    private void DJLMXieRuShiBai() { // 写卡失败
        showMsg(112, "写卡失败,请重试");
    }

    private void showMsg(int count, final String result) {

        Message msg = Message.obtain(); //从全局池中返回一个message实例，避免多次创建message（如new Message）
        msg.obj = result;
        if (count == 111) {
            // 显示Toast
            msg.what = 1471; //失败弹吐司
        } else if (count == 113) {
            msg.what = 1472;// 写卡成功(web端刷新用)
        } else {
            // 显示结果弹窗
            msg.what = 1470; //失败弹dialog
        }
        senHandler.sendMessage(msg);

    }

    private void dismissDialog() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
